<script setup>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import { ref, watch } from 'vue';

const arr = JSON.parse(localStorage.getItem('list')) || [
  { id: 1, name: '吃饭', done: true },
  { id: 2, name: '睡觉', done: true },
  { id: 3, name: '敲代码', done: false },
]
const list = ref(arr)

// 数据持久化
watch(list, (val) => {
  localStorage.setItem('list', JSON.stringify(val))
}, { deep: true })


// 修改状态
const changeDone = (id) => {
  // console.log('id', id);
  // 根据id查找到列表中的对象
  const obj = list.value.find(v => v.id === id) || {}
  // 把对象的状态取反
  obj.done = !obj.done
}
// 删除数据
const del = (id) => {
  // console.log('id', id);
  // 方法1，找到下标并且删除即可
  // const index = list.value.findIndex(v => v.id === id)
  // // console.log('index', index)
  // if (index !== -1) {
  //   list.value.splice(index, 1)
  // }

  // 写法2
  list.value = list.value.filter(v => v.id !== id)
}

// 添加数据
const addTodo = (name) => {
  list.value.unshift({
    // id: Date.now(),
    // id: new Date().getTime(),
    id: +new Date(),
    name,
    done: false
  })
}

// 全选反选
const changeAll = (bl) => {
  list.value.forEach(item => item.done = bl)
}

</script>

<template>
  <section class="todoapp">
    <TodoHeader @addTodo="addTodo"></TodoHeader>
    <TodoMain :list="list" @changeDone="changeDone" @del="del" @changeAll="changeAll"></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>

<style>
</style>
